//
//  SchoolViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2017/10/25.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "SchoolViewController.h"
#import "SchoolHeadViewCell.h"
#import "SchoolTeachViewCell.h"
#import "HotLbtModel.h"
#import "WWebViewController.h"
#import "ReportVideoModel.h"
#import "SchoolListViewController.h"
#import "UIImageView+WebCache.h"
#import "VideoDetailViewController.h"
#import "CheckNetwork.h"

@interface SchoolViewController ()<UITableViewDelegate,UITableViewDataSource,SchoolHeadViewCellDelegate>{
    int j;
    UIButton *recordBtn;
    UIButton *btnHot;
    UIButton *btnSw;
}

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *arrLbt;
@property (nonatomic, strong)NSMutableArray *arrData;
@property (nonatomic, strong)UIView *viewHead;

@end

@implementation SchoolViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;

    if ([WShareUtil sharedData].dicSleSymbol) {

        NSInteger tag = [[WShareUtil sharedData].dicSleSymbol[@"index"] integerValue];

        ReportVideoModel *reporModel = self.arrData[tag];
        if ([[WShareUtil sharedData].dicSleSymbol[@"chosen"] boolValue]) {
            reporModel.chosen = @"1";
        }
        [self.arrData replaceObjectAtIndex:tag withObject:reporModel];

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:1];
        //2.将indexPath添加到数组
        NSArray <NSIndexPath *> *indexPathArray = @[indexPath];
        //3.传入数组，对当前cell进行刷新
        [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
        [WShareUtil sharedData].dicSleSymbol = nil;
    }

    if ([WShareUtil sharedData].dicBuySymbol) {

        WLog(@"%@",[WShareUtil sharedData].dicBuySymbol);
        WLog(@"%@",[WShareUtil sharedData].dicBuySymbol[@"id"]);

        for (int i = 0; i < self.arrData.count; i++) {
            if ([[WShareUtil sharedData].dicBuySymbol[@"id"] isEqualToString:[self.arrData[i] strId]]) {

                ReportVideoModel *reporModel = self.arrData[i];
                if ([[WShareUtil sharedData].dicBuySymbol[@"boughten"] boolValue]) {
                    reporModel.boughten = @"1";
                }
                [self.arrData replaceObjectAtIndex:i withObject:reporModel];

                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
                //2.将indexPath添加到数组
                NSArray <NSIndexPath *> *indexPathArray = @[indexPath];
                //3.传入数组，对当前cell进行刷新
                [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
                [WShareUtil sharedData].dicBuySymbol = nil;
            }
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _arrLbt = [NSMutableArray array];
    _arrData = [NSMutableArray array];

    j = 1;
    NSArray *arrReturn = [WShareUtil readModelDataFromFile:@"schoolList"];

    if (arrReturn != nil && arrReturn.count > 0) {
        for (NSDictionary *dic in arrReturn) {
            ReportVideoModel *videoModel = [ReportVideoModel mj_objectWithKeyValues:dic];
            [self.arrData addObject:videoModel];
        }
    }

    // 获取数据方法
    NSDictionary *returnDic = [WShareUtil getDataWithUserDefaultsForKey: @"schoolLbtKcyg"];
    
    [WShareUtil sharedData].arrShOfAds = returnDic[@"lbt"];
    [WShareUtil sharedData].arrShOfTit = returnDic[@"kcyg"];
    for (NSDictionary *dic in returnDic[@"lbt"]) {
        HotLbtModel *lbtModel = [HotLbtModel mj_objectWithKeyValues:dic];
        [self.arrLbt addObject:lbtModel];
    }

    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"学堂";
    [self.view addSubview:self.tableView];
    [self.tableView.superview insertSubview:[UIView new] atIndex:0];
    [self schoolVcDataRequest];
    [self notifyRequestListData:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refershingView) name:@"LoginSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refershingView) name:@"LogoutSucceed" object:nil];
}

- (void)refershingView {
    [self.tableView.header beginRefreshing];
}

- (void)noWifiRefershingEnd {
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;
}

- (void)notifyRequestListData:(UIButton *)btn{

    if (recordBtn.tag == btn.tag && recordBtn != nil) {
        return;
    }
    if (btn.tag == 5001) {
        [self requestListDataStrNum:@"1" recommend:@"sw" isRefrsh:YES];
        [btnHot setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btnSw setTitleColor:WRGBColor(34, 136, 253) forState:UIControlStateNormal];
        j = 1;

    }else {
        [self requestListDataStrNum:@"1" recommend:@"hot" isRefrsh:YES];
        [btnHot setTitleColor:WRGBColor(34, 136, 253) forState:UIControlStateNormal];
        [btnSw setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        j = 1;
    }

    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self schoolVcDataRequest];
        if (btn.tag == 5001) {
            [self requestListDataStrNum:@"1" recommend:@"sw" isRefrsh:YES];
        }else {
            [self requestListDataStrNum:@"1" recommend:@"hot" isRefrsh:YES];
        }
        j = 1;
    }];

    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *num = [NSString stringWithFormat:@"%d",++j];
        if (btn.tag == 5001) {
            [self requestListDataStrNum:num recommend:@"sw" isRefrsh:NO];
        }else {
            [self requestListDataStrNum:num recommend:@"hot" isRefrsh:NO];
        }
    }];
    recordBtn = btn;
}

- (UITableView *)tableView {
    if (_tableView == nil) {

        if (_isMore) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64) style:UITableViewStylePlain];
        } else {
            
            if (XIPHONE) {
                _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT -110 -30) style:UITableViewStylePlain];
            }else{
                _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT - 110) style:UITableViewStylePlain];
            }
        }
        self.tableView.estimatedRowHeight =0;
        self.tableView.estimatedSectionHeaderHeight =0;
        self.tableView.estimatedSectionFooterHeight =0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//去掉横线
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0){
        return 1;
    }
    return _arrData.count;
}

- (UIView *)viewHead {
    if (!_viewHead) {
        _viewHead = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, 44)];
        _viewHead.backgroundColor = [UIColor whiteColor];
        btnHot = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 80, 44)];
        [btnHot setTitle:@"热点专讲" forState: UIControlStateNormal];
        btnHot.titleLabel.font = [UIFont systemFontOfSize:16];
        [btnHot setTitleColor:WRGBColor(34, 136, 253) forState:UIControlStateNormal];
        btnHot.tag = 5000;
        [btnHot addTarget:self action:@selector(notifyRequestListData:) forControlEvents:UIControlEventTouchUpInside];

        //小横线
        UILabel *lineLb = [[UILabel alloc]initWithFrame:CGRectMake(95, 12, 1, 20)];
        lineLb.backgroundColor = [UIColor lightGrayColor];
        [_viewHead addSubview:lineLb];
        
        btnSw = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 80, 44)];
        [btnSw setTitle:@"实务精讲" forState: UIControlStateNormal];
        btnSw.titleLabel.font = [UIFont systemFontOfSize:16];
        [btnSw setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btnSw.tag = 5001;
        [btnSw addTarget:self action:@selector(notifyRequestListData:) forControlEvents:UIControlEventTouchUpInside];

        [_viewHead addSubview:btnHot];
        [_viewHead addSubview:btnSw];
    }
    return _viewHead;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *view;
    if (section == 1) {
        view = self.viewHead;
        return view;
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSInteger height;
    if (section == 1){
        return height = 44;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger height;
    if (indexPath.section == 0){
        height = 340;
    }
    else {
        height = 100;
    }
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SCHOOLVIEWCELL"];

    if (indexPath.section == 0) {
        if (cell == nil) {
            SchoolHeadViewCell *headViewCell = [[[NSBundle mainBundle] loadNibNamed:@"SchoolHeadViewCell" owner:self options:nil] lastObject];
            headViewCell.delegate = self;
            cell = headViewCell;
        }
    }else if (indexPath.section == 1) {
        if (cell == nil) {
            SchoolTeachViewCell *teachViewCell = [[[NSBundle mainBundle] loadNibNamed:@"SchoolTeachViewCell" owner:self options:nil] lastObject];

            if (_arrData.count > 0 && _arrData) {

//                [teachViewCell.imgCell sd_setImageWithURL:[NSURL URLWithString:[_arrData[indexPath.row] imgsrc]] placeholderImage:[UIImage imageNamed:@"school_image.png"]];

                GifView *gifView = [WShareUtil animatedGifWithData:teachViewCell.imgCell];
                [teachViewCell.imgCell addSubview:gifView];

                [teachViewCell.imgCell sd_setImageWithURL:[NSURL URLWithString:[_arrData[indexPath.row] imgsrc]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    [gifView removeFromSuperview];
                }];

                if ([[_arrData[indexPath.row] chosen] boolValue]) {
                    teachViewCell.lbType.hidden = NO;
                    teachViewCell.lbType.text = @"已选课";
                    teachViewCell.lbType.backgroundColor = WRGBColor(235, 107, 12);
                } else if (![[_arrData[indexPath.row] chosen] boolValue] && [[_arrData[indexPath.row] boughten] boolValue]) {
                    teachViewCell.lbType.hidden = NO;
                    teachViewCell.lbType.text = @"已购买";
                    teachViewCell.lbType.backgroundColor = WRGBColor(208, 45, 39);
                }

                teachViewCell.lbNum.text = [NSString stringWithFormat:@"%@人学习过",[_arrData[indexPath.row] strView]];
                //价格与免费
                if ([[_arrData[indexPath.row] isfree] isEqualToString:@"true"]) {
                    teachViewCell.lbPrice.text = @"免费";
                    teachViewCell.lbPrice.textColor = [UIColor colorWithRed:0.37 green:0.71 blue:0.11 alpha:1];

                }else{
                    teachViewCell.lbPrice.text = [NSString stringWithFormat:@"¥%@",[_arrData[indexPath.row] charged]];

                }
                teachViewCell.lbTitle.text = [_arrData[indexPath.row] strTitle];

                [UILabel changeSpaceForLabel:teachViewCell.lbTitle];
            }
            cell = teachViewCell;
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)delegatScrollClick:(NSInteger)index {

    WLog(@"%@",[WShareUtil sharedData].arrShOfTit);
    WWebViewController *webVc = [[WWebViewController alloc] init];
    webVc.strTitle = @"课程预告";
    if ([WShareUtil sharedData].arrShOfTit[index]) {
        webVc.strUrl = [WShareUtil sharedData].arrShOfTit[index][@"link"];
    }
    [self.navigationController pushViewController:webVc animated:YES];
}

- (void)delegatiCarClick:(NSInteger)index {

    VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc] init];
    videoDetailVc.strId = [_arrLbt[index] link];
    videoDetailVc.symbol = School_Symbol;
    [self.navigationController pushViewController:videoDetailVc animated:YES];
}

- (void)delegatBtnClick:(UIButton *)button {

    SchoolListViewController *listVc = [[SchoolListViewController alloc]init];

    if (button.tag == 2000) {
        listVc.title = @"发票管理";
        listVc.strType = @"fpgl";
    }else if (button.tag == 2001) {
        listVc.title = @"申报及办税";
        listVc.strType = @"wssb";
    }else if (button.tag == 2002) {
        listVc.title = @"增值税";
        listVc.strType = @"zzsfp";
    }else if (button.tag == 2003) {
        listVc.title = @"地方税类";
        listVc.strType = @"dfsl";
    }else if (button.tag == 2004) {
        listVc.title = @"企业所得税";
        listVc.strType = @"sds";
    }else if (button.tag == 2005) {
        listVc.title = @"更多课程";
        listVc.strType = @"";
    }
    [self.navigationController pushViewController:listVc animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        return;
    }
    
    CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
    if (![checkNetwork isNetworkReachable]) {//没网
        return;
    } else {
        VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc] init];
        videoDetailVc.strId = [self.arrData[indexPath.row] strId];
        videoDetailVc.intTag = indexPath.row;
        videoDetailVc.symbol = School_Symbol;
        [self.navigationController pushViewController:videoDetailVc animated:YES];
    }
}

//轮播图、课程预告请求
- (void)schoolVcDataRequest {
    [WShareUtil sharedData].isShowWait = NO;

    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"revert":@"init"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        [WShareUtil sharedData].arrShOfAds = returnDic[@"lbt"];
        [WShareUtil sharedData].arrShOfTit = returnDic[@"kcyg"];

        [WShareUtil removeDataWithUserDefaultsForKey:@"schoolLbtKcyg"];
        [WShareUtil saveDataWithUserDefaultsSetObject:returnDic ForKey:@"schoolLbtKcyg"];

        for (NSDictionary *dic in returnDic[@"lbt"]) {
            HotLbtModel *lbtModel = [HotLbtModel mj_objectWithKeyValues:dic];
            [self.arrLbt addObject:lbtModel];
        }
        [self noWifiRefershingEnd];
        [self.tableView reloadData];

    } failure:^(NSError *error) {
        [self noWifiRefershingEnd];
        WLog(@"失败");
    } showProgress:YES];
}

- (void)requestListDataStrNum:(NSString *)pageNum recommend:(NSString *)recommend isRefrsh:(BOOL)isRefrsh{

    [WShareUtil sharedData].isShowWait = NO;

    NSDictionary *parametersDict;
    NSString *nologinuser;
    if ([WShareUtil sharedData].dicSession) {
        parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"revert":@"paginate",@"recommend":recommend,@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};

    } else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"revert":@"paginate",@"recommend":recommend,@"nologinuser":nologinuser,@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        [WShareUtil removeModelDataWithFile:@"schoolList"];

        if (isRefrsh) {
            [self.arrData removeAllObjects];
        }
        
        for (NSDictionary *dic in returnDic[@"data"]) {
            ReportVideoModel *videoModel = [ReportVideoModel mj_objectWithKeyValues:dic];
            [self.arrData addObject:videoModel];
        }

        [WShareUtil saveModelData:self.arrData WithFile:@"schoolList"];

        [self noWifiRefershingEnd];
        [self.tableView reloadData];
//        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
//        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

        if ([returnDic[@"data"] count] < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.tableView.footer endRefreshingWithNoMoreData];
        }


    } failure:^(NSError *error) {
        [self noWifiRefershingEnd];
        WLog(@"失败");
    } showProgress:YES];
}

@end
